/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) 2010 Roman Divotkey

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.java2d;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;

import javax.swing.JPanel;

/**
 * Screen used to diaplay output within Java Swing applications.
 */
public class WindowedScreen extends Screen implements HierarchyListener {
        
    /** Swing component used to display output. */
    private JPanel panel;
    
    /** Back buffer image used to implement double buffering. */
    private Image backbuffer;
    
    /** Indicates if this screen is fully initialized. */
    private boolean initialized = false;

    /**
     * Creates a new WindowedScreen instance.
     * 
     * @param screenSize  Dimension object defining height and width 
     *                    of this screen.
     */
    public WindowedScreen(Dimension screenSize) {
        super(screenSize);
        
        // initialize panel component
        panel = new MyPanel();
        panel.setPreferredSize(size);
        panel.setMinimumSize(size);
        panel.setMaximumSize(size);
        panel.setIgnoreRepaint(true);
        panel.setDoubleBuffered(false);       
        panel.setOpaque(true);
                
        // register as hierarchy listener in order to get informed when our
        // panel becomes visible
        panel.addHierarchyListener(this);
    };
    
    public WindowedScreen(int x, int y) {
    	this(new Dimension(x, y));
	}

	/**
     * Sets initialized to <code>true</code>. This method must be 
     * synchronized because initialization of our back buffer image
     * will be called from Java event dispatch thread.
     * 
     * @param value
     */
    private synchronized void setInitialized(boolean value) {
    	initialized = value;
    	notify();
    }    
    
    /**
     * Initializes our back buffer image. Our panel component must
     * be visible in order to make this method work.
     */
    private void initialize() {
    	if (backbuffer != null) return;
	
        backbuffer = panel.createImage(panel.getSize().width, panel.getSize().height);   
        panel.setFocusable(true);
        setInitialized(true);
    }    
    
    @Override
    public Component getComponent() {
        return panel;
    }
        
    @Override
    public synchronized void waitUntilReady() {
    	while (!initialized) {
    		try {
    			wait();
    		} catch (InterruptedException e) {
    			Thread.currentThread().interrupt();
    		}
    	}
    }    
    
    
    @Override
    public Graphics2D getGraphicsContext() {
        return (Graphics2D) backbuffer.getGraphics();
    }

    @Override
    public void update() {
        Graphics g = panel.getGraphics();
        g.drawImage(backbuffer, 0, 0, panel);    
        g.dispose();
    }
    
    
	@Override
	public void hideMouseCursor() {
		// intentionally left empty
	}

	@Override
	public void showMouseCursor() {
		// intentionally left empty
	}
	
	@Override
	public GraphicsConfiguration getGraphicsConfiguration() {
		return this.panel.getGraphicsConfiguration();
	}
    
    //////////////// HierarchyListener interface ////////////////
    
    /**
     * Called when the hierarchy has been changed.
     */
    public void hierarchyChanged(HierarchyEvent event) {
    	if (backbuffer != null) return;
	
    	long query = event.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED;
	
    	if ( query != 0 && panel.isShowing() ) { 
    		initialize();
    	}
    }    
    
	@Override
	public boolean isFullscreen() {
		return false;
	}
    
    /** 
     * Swing Component used to display output.
     */
    private class MyPanel extends JPanel {

    	private static final long serialVersionUID = 1L;
	
    	@Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            
            if (backbuffer != null) {
                g.drawImage(backbuffer, 0, 0, null);
            }
        }        
    }
}